const query = require('../model/index')

/**
 * @func addArticle
 * @desc 新增文章
 * @param {username} 用户名
 * @param {title} 文章标题
 * @param {text} 内容
 * @param {tags} 标签
 */

exports.addArticle = async (req, res, next) => {
  const { user_name, title, text, tags } = req.body
  //   const sqStr = `select * from user_info where username=?`
  const creat_time = new Date().toLocaleDateString()
  // console.log(creat_time)
  // return

  const sqStr = `insert into article_info(user_name,title,text,tags,creat_time)
  values ('${user_name}','${title}','${text}','${tags}','${creat_time}')`

  const result = await query(sqStr)
  if (result.length) return res.cc('发布失败', 99999)
  res.cc('success', 0, result)
}

/**
 * @func searchArticle
 * @desc 查询文章列表
 * @param {}
 * @return {list} Array
 */
exports.searchArticle = async (req, res, next) => {
  const { current_page, page_size, author, keywords } = req.body
  const start_size = (current_page - 1 || 0) * (page_size || 2)
  let whereStr = `AND user_name='${author}'`
  if (!author) whereStr = ''

  let likeStr = `AND title LIKE '%${keywords}%' OR text LIKE '%${keywords}%'`
  if(!keywords) likeStr =  ''

  const sqStr = `select * from article_info Where 1=1 ${whereStr} ${likeStr} ORDER BY article_id DESC limit ${start_size},${
    page_size || 2
  }`

  // console.log(sqStr)

  const sqlTotal = `select count(1) as total from article_info Where 1=1 ${whereStr} ${likeStr}`

  // console.log('查询总条数',sqlTotal);

  const result = await query(sqStr)
  const totalResult = await query(sqlTotal)
  // console.log(result)
  // console.log(totalResult)
  if (!result.length) return res.cc('查询失败', 999999)
  const return_params = {
    list: result,
    pageInfo: {
      total: totalResult[0].total || 0,
    },
  }
  res.cc('success', 0, return_params)
}

/**
 * @func getPrevNextArticle
 * @desc 获取上一篇 || 下一篇文章
 * @param {page_type} pre、 next
 * @param {id} 文章id
 * @return {}
 */
exports.getPrevNextArticle = async (req, res, next) => {
  let sql
  const { page_type, id } = req.body
  console.log(page_type)
  console.log(id)

  if (page_type === 'pre') {
    sql = `SELECT * FROM article_info a WHERE a.article_id > ${id} ORDER BY a.article_id DESC LIMIT 0,1`
  } else {
    sql = `SELECT * FROM article_info a WHERE a.article_id < ${id} ORDER BY a.article_id DESC LIMIT 0,1`
  }

  console.log(sql)
  const result = await query(sql, null, 'object')

  if (!Object.keys(result).length) res.cc('已经是首页或者尾页，获取文章失败', 999999, result)
  else res.cc('success', 0, result)
}
